using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace GameOverlayWPF
{
    public class ImageLoadedEventArgs : EventArgs
    {
        public string Url { get; set; }
        public BitmapImage Image { get; set; }
    }
    
    public class ImageUrlConverter : IValueConverter
    {
        public static event EventHandler<ImageLoadedEventArgs> ImageLoaded;
        
        // 内存缓存
        private static readonly Dictionary<string, BitmapImage> _imageCache = new Dictionary<string, BitmapImage>();
        private static readonly Dictionary<string, bool> _loadingUrls = new Dictionary<string, bool>();
        private static BitmapImage _defaultAvatar = null;
        private static readonly object _lockObject = new object();
        private static readonly HttpClient _httpClient = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(30),
            MaxResponseContentBufferSize = 2 * 1024 * 1024
        };
        
        // 记录加载失败的URL和重试次数
        private static readonly HashSet<string> _failedUrls = new HashSet<string>();
        private static readonly Dictionary<string, int> _retryCount = new Dictionary<string, int>();
        private const int MAX_RETRY_COUNT = 2;
        
        // 并发控制
        private static readonly System.Threading.SemaphoreSlim _loadingSemaphore = new System.Threading.SemaphoreSlim(6, 6); // 最多6个并发加载
        private static int _loadingCount = 0;
        private static readonly object _loadingCountLock = new object();
        
        // 磁盘缓存配置
        private static readonly string _cacheDirectory;
        private const int MAX_CACHE_SIZE = 200;
        
        static ImageUrlConverter()
        {
            // 初始化缓存目录
            _cacheDirectory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "GameOverlayWPF",
                "Cache",
                "Images"
            );
            
            try
            {
                if (!Directory.Exists(_cacheDirectory))
                {
                    Directory.CreateDirectory(_cacheDirectory);
                }
                System.Diagnostics.Debug.WriteLine($"图片缓存目录: {_cacheDirectory}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"创建缓存目录失败: {ex.Message}");
            }
        }

        private static BitmapImage GetDefaultAvatar()
        {
            if (_defaultAvatar != null)
                return _defaultAvatar;

            lock (_lockObject)
            {
                if (_defaultAvatar != null)
                    return _defaultAvatar;

                try
                {
                    // 创建一个简单的1x1像素透明图作为占位符
                    var img = new BitmapImage();
                    img.BeginInit();
                    // 使用一个有效的在线占位图，或者创建空白图
                    // 使用UI Avatar生成器 - 快速且可靠
                    img.UriSource = new Uri("https://ui-avatars.com/api/?name=U&size=60&background=666666&color=fff", UriKind.Absolute);
                    img.CacheOption = BitmapCacheOption.OnLoad;
                    img.DecodePixelWidth = 60;
                    img.DecodePixelHeight = 60;
                    img.EndInit();
                    // 不要Freeze，因为是异步加载
                    _defaultAvatar = img;
                    return img;
                }
                catch
                {
                    // 如果失败，返回null让WPF使用默认处理
                    return null;
                }
            }
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                System.Diagnostics.Debug.WriteLine("⚠ 图片URL为空，使用默认头像");
                return GetDefaultAvatar();
            }

            string url = value.ToString()?.Trim();
            if (string.IsNullOrEmpty(url))
            {
                System.Diagnostics.Debug.WriteLine("⚠ 图片URL为空字符串，使用默认头像");
                return GetDefaultAvatar();
            }
            
            System.Diagnostics.Debug.WriteLine($"→ 开始加载图片: {url}");
            
            // 1. 检查内存缓存
            lock (_lockObject)
            {
                if (_imageCache.TryGetValue(url, out BitmapImage cachedImage))
                {
                    return cachedImage;
                }
                
                // 如果之前加载失败，直接返回默认头像，不再重试
                if (_failedUrls.Contains(url))
                {
                    System.Diagnostics.Debug.WriteLine($"⊗ 跳过加载失败的图片: {url}");
                    return GetDefaultAvatar();
                }
                
                // 如果正在加载，返回默认头像
                if (_loadingUrls.ContainsKey(url))
                {
                    return GetDefaultAvatar();
                }
            }
            
            // 2. 检查磁盘缓存
            var cachedFilePath = GetCachedFilePath(url);
            if (File.Exists(cachedFilePath))
            {
                try
                {
                    var bitmap = LoadFromFile(cachedFilePath);
                    if (bitmap != null)
                    {
                        // 加入内存缓存
                        lock (_lockObject)
                        {
                            if (!_imageCache.ContainsKey(url))
                            {
                                _imageCache[url] = bitmap;
                            }
                        }
                        System.Diagnostics.Debug.WriteLine($"从磁盘缓存加载: {url}");
                        return bitmap;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"读取磁盘缓存失败: {ex.Message}");
                    // 删除损坏的缓存文件
                    try { File.Delete(cachedFilePath); } catch { }
                }
            }

            try
            {
                BitmapImage bitmap;
                
                // 文件路径支持
                if (File.Exists(url))
                {
                    bitmap = LoadFromFile(url);
                }
                else if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    // 异步加载网络图片 - 立即返回占位符
                    lock (_lockObject)
                    {
                        _loadingUrls[url] = true;
                    }
                    
                    // 后台加载图片
                    Task.Run(async () => await LoadImageAsync(url));
                    
                    // 立即返回默认头像，图片加载完成后会自动更新
                    return GetDefaultAvatar();
                }
                else
                {
                    // 其他情况按相对/绝对Uri尝试
                    bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    // 移除像素限制，使用原始尺寸以获得更好的质量
                    // bitmap.DecodePixelWidth = 60;
                    // bitmap.DecodePixelHeight = 60;
                    bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
                
                // 添加到缓存
                if (bitmap != null)
                {
                    lock (_lockObject)
                    {
                        if (!_imageCache.ContainsKey(url))
                        {
                            // 清理过大的缓存
                            if (_imageCache.Count >= MAX_CACHE_SIZE)
                            {
                                // 移除最旧的50个条目
                                var keysToRemove = new List<string>();
                                int count = 0;
                                foreach (var key in _imageCache.Keys)
                                {
                                    keysToRemove.Add(key);
                                    if (++count >= 50) break;
                                }
                                foreach (var key in keysToRemove)
                                {
                                    _imageCache.Remove(key);
                                }
                            }
                            _imageCache[url] = bitmap;
                        }
                    }
                    return bitmap;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"图片加载异常: {url} - {ex.Message}");
            }
            
            return GetDefaultAvatar();
        }
        
        private BitmapImage LoadFromFile(string filePath)
        {
            try
            {
                using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var ms = new MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;
                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    // 移除像素限制，使用原始尺寸以获得更好的质量
                    // bitmap.DecodePixelWidth = 60;
                    // bitmap.DecodePixelHeight = 60;
                    // 优化渲染质量
                    bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                    bitmap.StreamSource = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();
                    return bitmap;
                }
            }
            catch
            {
                return null;
            }
        }
        
        private string GetCachedFilePath(string url)
        {
            // 使用SHA256生成文件名，避免URL中的非法字符
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(url));
                var hashString = BitConverter.ToString(hash).Replace("-", "").ToLower();
                return Path.Combine(_cacheDirectory, hashString + ".jpg");
            }
        }
        
        private async Task<BitmapImage> LoadImageAsync(string url, bool isRetry = false)
        {
            // 获取当前重试次数
            int currentRetry = 0;
            lock (_lockObject)
            {
                if (_retryCount.TryGetValue(url, out int retry))
                {
                    currentRetry = retry;
                }
            }
            
            // 并发控制
            await _loadingSemaphore.WaitAsync();
            lock (_loadingCountLock)
            {
                _loadingCount++;
                if (_loadingCount % 5 == 0)
                {
                    System.Diagnostics.Debug.WriteLine($"📊 当前并发加载图片数: {_loadingCount}");
                }
            }
            
            try
            {
                // 下载图片数据（带重试）
                var imageData = await _httpClient.GetByteArrayAsync(url);
                
                // 保存到磁盘缓存
                try
                {
                    var cachedFilePath = GetCachedFilePath(url);
                    await File.WriteAllBytesAsync(cachedFilePath, imageData);
                    System.Diagnostics.Debug.WriteLine($"图片已缓存到磁盘: {url}");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"保存磁盘缓存失败: {ex.Message}");
                }
                
                // 在UI线程创建BitmapImage
                await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        var bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        // 移除像素限制，使用原始尺寸以获得更好的质量
                        // bitmap.DecodePixelWidth = 60;
                        // bitmap.DecodePixelHeight = 60;
                        // 优化渲染质量
                        bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                        bitmap.StreamSource = new MemoryStream(imageData);
                        bitmap.EndInit();
                        bitmap.Freeze();
                        
                        lock (_lockObject)
                        {
                            _loadingUrls.Remove(url);
                            if (!_imageCache.ContainsKey(url))
                            {
                                // 清理过大的缓存
                                if (_imageCache.Count >= MAX_CACHE_SIZE)
                                {
                                    var keysToRemove = new List<string>();
                                    int count = 0;
                                    foreach (var key in _imageCache.Keys)
                                    {
                                        keysToRemove.Add(key);
                                        if (++count >= 50) break;
                                    }
                                    foreach (var key in keysToRemove)
                                    {
                                        _imageCache.Remove(key);
                                    }
                                }
                                _imageCache[url] = bitmap;
                            }
                        }
                        
                        System.Diagnostics.Debug.WriteLine($"✓ 图片加载成功: {url}");
                        
                        // 触发UI刷新 - 通知ListBox重新渲染
                        try
                        {
                            ImageLoaded?.Invoke(null, new ImageLoadedEventArgs { Url = url, Image = bitmap });
                        }
                        catch { }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"✗ UI线程创建图片失败: {url} - {ex.Message}");
                        lock (_lockObject)
                        {
                            _loadingUrls.Remove(url);
                            _failedUrls.Add(url); // 记录失败的URL
                        }
                    }
                }, DispatcherPriority.Background);
            }
            catch (TaskCanceledException ex)
            {
                // 超时异常 - 根据重试次数决定是否重试
                lock (_lockObject)
                {
                    _loadingUrls.Remove(url);
                    if (currentRetry < MAX_RETRY_COUNT)
                    {
                        System.Diagnostics.Debug.WriteLine($"⚠ 图片加载超时，准备重试 ({currentRetry + 1}/{MAX_RETRY_COUNT}): {url}");
                        // 延迟后重试
                        Task.Delay(1000).ContinueWith(_ => Task.Run(async () => await LoadImageAsync(url)));
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"✗ 图片加载超时，已达最大重试次数: {url} - {ex.Message}");
                        _failedUrls.Add(url);
                        _retryCount.Remove(url);
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // HTTP请求异常 - 可能是网络问题，尝试重试
                lock (_lockObject)
                {
                    _loadingUrls.Remove(url);
                    if (currentRetry < MAX_RETRY_COUNT)
                    {
                        System.Diagnostics.Debug.WriteLine($"⚠ 图片加载失败，准备重试 ({currentRetry + 1}/{MAX_RETRY_COUNT}): {url} - {ex.Message}");
                        Task.Delay(1000).ContinueWith(_ => Task.Run(async () => await LoadImageAsync(url)));
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"✗ 图片HTTP请求失败，已达最大重试次数: {url} - {ex.Message}");
                        _failedUrls.Add(url);
                        _retryCount.Remove(url);
                    }
                }
            }
            catch (Exception ex)
            {
                // 其他异常 - 不重试
                System.Diagnostics.Debug.WriteLine($"✗ 异步加载图片失败: {url} - {ex.GetType().Name}: {ex.Message}");
                lock (_lockObject)
                {
                    _loadingUrls.Remove(url);
                    _failedUrls.Add(url);
                    _retryCount.Remove(url);
                }
            }
            finally
            {
                // 释放并发控制信号量
                lock (_loadingCountLock)
                {
                    _loadingCount--;
                }
                _loadingSemaphore.Release();
            }
            
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        /// <summary>
        /// 清理磁盘缓存（可选：保留最近使用的文件）
        /// </summary>
        public static void ClearDiskCache(bool keepRecent = false, int keepCount = 100)
        {
            try
            {
                if (!Directory.Exists(_cacheDirectory))
                    return;
                
                var files = new DirectoryInfo(_cacheDirectory).GetFiles("*.jpg");
                
                if (keepRecent && files.Length > keepCount)
                {
                    // 按修改时间排序，删除旧文件
                    var filesToDelete = files
                        .OrderByDescending(f => f.LastAccessTime)
                        .Skip(keepCount)
                        .ToList();
                    
                    foreach (var file in filesToDelete)
                    {
                        try { file.Delete(); } catch { }
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"清理了 {filesToDelete.Count} 个旧缓存文件");
                }
                else
                {
                    // 删除所有缓存
                    foreach (var file in files)
                    {
                        try { file.Delete(); } catch { }
                    }
                    System.Diagnostics.Debug.WriteLine($"清理了 {files.Length} 个缓存文件");
                }
                
                // 清理内存缓存
                lock (_lockObject)
                {
                    _imageCache.Clear();
                    _failedUrls.Clear(); // 也清理失败URL列表，允许重试
                    _retryCount.Clear(); // 清理重试计数
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"清理缓存失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取缓存统计信息
        /// </summary>
        public static string GetCacheStats()
        {
            try
            {
                if (!Directory.Exists(_cacheDirectory))
                    return "缓存目录不存在";
                
                var files = new DirectoryInfo(_cacheDirectory).GetFiles("*.jpg");
                var totalSize = files.Sum(f => f.Length) / 1024.0 / 1024.0; // MB
                
                int memoryCount;
                lock (_lockObject)
                {
                    memoryCount = _imageCache.Count;
                }
                
                return $"磁盘缓存: {files.Length} 个文件, {totalSize:F2} MB | 内存缓存: {memoryCount} 个";
            }
            catch (Exception ex)
            {
                return $"获取统计失败: {ex.Message}";
            }
        }
    }
}

